//GAME
var imageUrl = imagesUrl ? imagesUrl : 'images/';
var GAME = (function (g, cjs) {
    var CVS,
        SW, SH,//宽高
        canvas,
        stage,
        gameMain,//游戏主容器
        tipsCont,
        lineCont,
        loader;
    var GUAN = 0;
    var MAP;
    var colorArr = ["#00ff80", "#9966cc", "#8ae51b", "#4cb4e7", "#e9f01d", "#82a6f5", "#f17c67"];
    var margin = 28,
        padding = 12,
        boxw = 110,
        tipsW = 4,
        lineW = boxw - padding * 2,
        boxColor = "#ffffff",
        lineColor = "#8ae51b";
    var LINE, TIPS;
    var boxPool = [],
        pointPool = [];
    var curIndex = 0;
    var ROW, COL;
    var finishNum = 0;
    var isOver = true;
    var isTips = false;
    //point item=>{x:0,y:0}
    g.init = function () {
        //common settings
        stage = INIT.stage;
        loader = INIT.loader;
        SW = INIT.width;
        SH = INIT.height;
        gameMain = new cjs.Container();
        tipsCont = new cjs.Container();
        lineCont = new cjs.Container();
        LINE = new createjs.Shape();
        TIPS = new createjs.Shape();
        lineCont.addChild(LINE);
        tipsCont.addChild(TIPS);
        stage.addChild(gameMain, tipsCont, lineCont);
        g.onPress();
		// g.start();
    };
    //开始游戏，绑定事件
    g.start = function () {
        isOver = false;
        isTips = false;
        g.getMap();
        cjs.Touch.enable(stage);
        INIT.startTick();
        g.createMap();
    }
    g.getMap = function (d) {
        MAP = GAMEDATA.map[GUAN];
    }
    g.createLine = function (x, y) {
        LINE.graphics.clear();
        var fx = x + padding - boxw / 2,
            fy = y + lineW / 2 + padding - boxw / 2;
        LINE.graphics.setStrokeStyle(lineW).beginStroke(lineColor).moveTo(fx, fy).lineTo(fx + lineW, fy);
    }
    g.onPress = function () {
        stage.addEventListener("pressmove", function (e) {
            if (!isOver) {
                g.checkPositon(e.stageX, e.stageY);
            }
        });
    }
    g.drawLine = function () {
        LINE.graphics.clear();
        var x1 = boxPool[pointPool[0]].x + padding - boxw / 2,
            y1 = boxPool[pointPool[0]].y + lineW / 2 + padding - boxw / 2;
        LINE.graphics.setStrokeStyle(lineW).beginStroke(lineColor).moveTo(x1, y1).lineTo(x1 + lineW, y1).moveTo(x1 + lineW / 2, y1);
        pointPool.forEach(function (item, index) {
            var r = boxPool[item];
            if (index > 0) {
                if (pointPool.length > 1 && index == pointPool.length - 1) {
                    var disX = 0,
                        disY = 0;
                    var last = pointPool[index - 1];
                    switch (last) {
                        //左
                        case item - 1:
                            disX = lineW / 2;
                            break;
                        //右
                        case item + 1:
                            disX = -lineW / 2;
                            break;
                        //上
                        case item - ROW:
                            disY = lineW / 2;
                            break;
                        //下
                        case item + ROW:
                            disY = -lineW / 2;
                            break;
                    }
                    LINE.graphics.lineTo(r.x + disX, r.y + disY).moveTo(r.x - disX / 2, r.y - disY / 2);
                } else {
                    LINE.graphics.lineTo(r.x, r.y);
                }
            }
        });
        if (pointPool.length == finishNum && !isOver) {
            console.log("finish");
            isOver = true;
            g.nextGuan();
        }
    }
    g.drawTips = function () {
        if (!isOver && !isTips && MAP.l) {
            isTips = true;
            var points = MAP.l;
            TIPS.graphics.clear();
            var p1 = boxPool[points[0]],
                x = p1.x,
                y = p1.y;
            TIPS.graphics.setStrokeStyle(tipsW).beginStroke(lineColor).moveTo(x, y);
            points.forEach(function (item, index) {
                if (index > 0) {
                    var p = boxPool[item];
                    TIPS.graphics.lineTo(p.x, p.y);
                }
            });
            getRemindList();
        } else {

        }
    }
    g.changeColor = function () {
        var len = colorArr.length,
            rand = parseInt(len * Math.random());
        lineColor = colorArr[rand];
    }
    g.pulseBox = function (index) {
        var _scale = 0.8;
        var r = boxPool[index];
        cjs.Tween.get(r).to({scaleX: _scale, scaleY: _scale}, 100).to({scaleX: 1, scaleY: 1}, 100);
    }
    g.createMap = function () {
        var map = MAP,
            mt = map.t.split("x");
        var row = mt[0],
            col = mt[1],
            marginx = (6 - row) * 0.5 * (boxw + margin),
            marginy = (6 - col) * 0.5 * (boxw + margin);
        ROW = +row;
        COL = +col;
        boxPool = [];
        pointPool = [];
        var n = 0;
        map.a.forEach(function (item, index) {
            if (item != 0) {
                var x = marginx + (index % row) * (boxw + margin) + boxw / 2,
                    y = marginy + parseInt(index / row) * (boxw + margin) + boxw / 2;
                if (item == 2) {
                    curIndex = index;
                    g.createLine(x, y);
                    pointPool.push(index);
                }
                g.createBox(x, y, index);
                n++;
            } else {
                boxPool.push(null);
            }
        });
        finishNum = n;
    }
    g.createBox = function (x, y, t) {
        var rect = new createjs.Shape();
        rect.graphics.beginFill(boxColor).drawRect(0, 0, boxw, boxw);
        rect.x = x;
        rect.y = y;
        rect.regX = boxw / 2;
        rect.regY = boxw / 2;
//		rect.isLined = curIndex == t ? true : false;
        rect.boxType = t;
        gameMain.addChild(rect);
        boxPool.push(rect);
    }
    g.checkPositon = function (sx, sy) {
        for (var p = 0; p < boxPool.length; p++) {
            var item = boxPool[p];
            //非null为有点
            if (item && p != curIndex) {
                //寻找邻居
                var top = (p + ROW) <= boxPool.length && (p + ROW) == curIndex,//上
                    left = (p + 1) % ROW != 0 && (p + 1 == curIndex),//左
                    right = p % ROW != 0 && (p - 1) == curIndex,//右
                    bottom = p - ROW >= 0 && p - ROW == curIndex;//下
                if (top || left || right || bottom) {
                    if (sx >= item.x - boxw / 2 && sx <= item.x + boxw / 2 && sy >= item.y - boxw / 2 && sy <= item.y + boxw / 2) {
                        //没有在池内，新的没有画到的点
                        if (pointPool.indexOf(p) < 0) {
                            pointPool.push(p);
                            curIndex = p;
                            g.pulseBox(p);
                        } else if (pointPool.length > 1 && pointPool[pointPool.length - 2] == p) {
                            pointPool.pop();
                            curIndex = p;
                        }
                        g.drawLine();
                        return true;
                    }
                }
            }
        }
    }
    g.updateGQ = function (g) {
        if (g > GAMEDATA.map.length) {
            $(".game").addClass("hide");
            $(".pass").removeClass("hide");
            document.getElementById("bgm").pause();
//			showAlert("下一关暂未开放！");
            return false;
        }
        GUAN = parseInt(g) - 1;
        $(".game-guanqia-number").text("第" + g + "关");
        return true;
    }
    g.nextGuan = function () {
        //闯关成功且是新关
        if (globalData.nextGameToken && GUAN == globalData.currentGuan) {
            finishGame(function (r) {
                g.toNext();
            });
        } else {
            //直接下一关
            g.toNext();
        }

    }
    g.toNext = function () {
        var alpha = 0.75,
            speed = 120;
        if (GUAN + 1 < GAMEDATA.map.length) {
            $(".guanqia-list li").eq(GUAN + 1).addClass("active");
        }
        cjs.Tween.get(stage).to({alpha: alpha}, speed).to({alpha: 1}, speed).to({alpha: alpha}, speed).to({alpha: 1}, speed).to({alpha: 0}, 600).call(function () {
            gameMain.removeAllChildren();
            TIPS.graphics.clear();
            LINE.graphics.clear();
            if (g.updateGQ(GUAN + 2)) {
                g.changeColor();
                g.getMap();
                g.createMap();
                cjs.Tween.get(stage).to({alpha: 1}, 600).call(function () {
                    isOver = false;
                    isTips = false;
//					console.log("G:" + GUAN);
//					console.log("cg:" + globalData.currentGuan)
                    if (GUAN == globalData.currentGuan) {
                        beginGame(GUAN + 1);
                    }
                });
            } else {
                stage.alpha = 1;
            }
        });
    }
    //over
    g.over = function () {
        //stop render
        isOver = true;
        curIndex = 0;
        gameMain.removeAllChildren();
        TIPS.graphics.clear();
        LINE.graphics.clear();
        cjs.Touch.disable(stage);
        INIT.stopTick();
    }
    g.onProgress = function (p) {
        var per = (p / 1 * 100 | 0) + '%';
    }
    g.onComplete = function () {
        console.log("加载完毕！");
        g.init();
    }
    return g;
})(window.GAME || {}, createjs);

//init canvas

//加载资源
var manifest = [
    {src: "circle_bg.png", id: "dot"}
];
//初始化
window.INIT = new initCjs({
    'id': 'canvas',//canvas的id
    'url': imagesUrl,//资源路径
    'width': 800,
    'height': 800,
    'frameRate': 60,//刷新帧率
    'useSound': true,//是否使用音频sound.js
    'scaleMode': 'noScale',//适配模式:exactFit | fixedWidth | noScale | showAll
    'preload': manifest,//加载资源组:Array | String | Object
    'autoLoad': true,//是否自动加载
    'autoRender': false,
    'bgColor': 'tranparent',
    'onProgress': function(){
        GAME.onProgress();
    },//加载中回调
    'onComplete': function(){
        initGuanqia(100,0);
        GAME.onComplete();
    } ,//加载完成回调
    'onError': function (msg) {
        console.log(msg);
    }
});